<template>
  <div class="p-2">
    <el-row :gutter="20">
      <el-col :lg="4" :xs="24" style="">
        <el-card shadow="hover">
          <el-tree ref="tree" :load="loadNode" :props="props" lazy style="max-width: 600px" @node-click="handleClick" />
        </el-card>
      </el-col>
      <el-col :lg="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="search">
            <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="68px">
              <el-form-item label="房屋编号" prop="roomNum">
                <el-input v-model="queryParams.roomNum" clearable placeholder="请输入房屋编号" style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </transition>
        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:floor:add']" :disabled="floorAddFlag" icon="Plus" plain type="primary" @click="handleAddFloor">
                  添加楼栋
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:floor:edit']" :disabled="floorSingle" icon="Edit" plain type="success" @click="handleUpdateFloor"
                  >修改楼栋
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:floor:remove']" :disabled="floorMultiple" icon="Delete" plain type="danger" @click="handleDeleteFloor"
                  >删除楼栋
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  v-hasPermi="['system:buildingUnit:add']"
                  :disabled="unitAddFlag"
                  icon="Plus"
                  plain
                  type="primary"
                  @click="handleAddBuildingUnit"
                >
                  添加单元
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  v-hasPermi="['system:buildingUnit:edit']"
                  :disabled="unitSingle"
                  icon="Edit"
                  plain
                  type="success"
                  @click="handleUpdateBuildingUnit"
                  >修改单元
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  v-hasPermi="['system:buildingUnit:remove']"
                  :disabled="unitMultiple"
                  icon="Delete"
                  plain
                  type="danger"
                  @click="handleDeleteBuildingUnit"
                  >删除单元
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:buildingRoom:add']" :disabled="roomAddFlag" icon="Plus" plain type="primary" @click="handleAddRoom">
                  添加房屋
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  v-hasPermi="['system:buildingRoom:edit']"
                  :disabled="roomSingle"
                  icon="Edit"
                  plain
                  type="success"
                  @click="handleUpdateRoom()"
                  >修改房屋
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  v-hasPermi="['system:buildingRoom:remove']"
                  :disabled="roomMultiple"
                  icon="Delete"
                  plain
                  type="danger"
                  @click="handleDeleteRoom()"
                  >删除房屋
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:buildingRoom:export']" icon="Download" plain type="warning" @click="handleExportRoom"
                  >导出房屋信息
                </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="buildingRoomList" @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" width="55" />
            <el-table-column align="center" label="房屋编号" prop="roomNum" />
            <el-table-column align="center" label="房屋楼层" prop="layer" />
            <el-table-column align="center" label="室" prop="section">
              <template #default="scope">
                <dict-tag :options="sys_section_list" :value="scope.row.section" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="户型" prop="apartment">
              <template #default="scope">
                <dict-tag :options="sys_apartment_list" :value="scope.row.section" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="建筑面积" prop="builtUpArea" />
            <el-table-column align="center" label="算费系数" prop="feeCoefficient" />
            <!--            <el-table-column align="center" label="户主" prop="userId" />-->
            <el-table-column align="center" label="房屋状态" prop="state">
              <template #default="scope">
                <dict-tag :options="sys_room_state" :value="scope.row.section" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="小区名称" prop="communityName" />
            <el-table-column align="center" label="房屋类型" prop="roomType">
              <template #default="scope">
                <dict-tag :options="sys_room_type" :value="scope.row.roomType" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="室内面积" prop="roomArea" />
            <el-table-column align="center" label="租金" prop="roomRent" />
            <el-table-column align="center" label="备注" prop="remark" />
            <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button
                    v-hasPermi="['system:buildingRoom:edit']"
                    icon="Edit"
                    link
                    type="primary"
                    @click="handleUpdateRoom(scope.row)"
                  ></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button
                    v-hasPermi="['system:buildingRoom:remove']"
                    icon="Delete"
                    link
                    type="primary"
                    @click="handleDeleteRoom(scope.row)"
                  ></el-button>
                </el-tooltip>
                <!--                <el-tooltip content="人员管理" placement="top" v-if="scope.row.roleId !== 1">-->
                <!--                  <el-button link type="primary" icon="User" @click="handleAuthUser(scope.row)" v-hasPermi="['system:role:edit']"></el-button>-->
                <!--                </el-tooltip>-->
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total>0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>
    <!-- 添加或修改房屋对话框 -->
    <el-dialog v-model="roomDialog.visible" :title="roomDialog.title" append-to-body width="500px">
      <el-form ref="buildingRoomFormRef" :model="roomForm" :rules="roomRules" label-width="80px">
        <el-form-item label="房屋编号" prop="roomNum">
          <el-input v-model="roomForm.roomNum" placeholder="请输入房屋编号" />
        </el-form-item>
        <el-form-item label="房屋楼层" prop="layer">
          <el-input v-model="roomForm.layer" placeholder="请输入层数" />
        </el-form-item>
        <el-form-item label="房屋户型" prop="section">
          <el-select v-model="roomForm.section" placeholder="请选择室" style="width: 190px">
            <el-option v-for="dict in sys_section_list" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
          <el-select v-model="roomForm.apartment" placeholder="请选择厅" style="width: 190px">
            <el-option v-for="dict in sys_apartment_list" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建筑面积" prop="builtUpArea">
          <el-input v-model="roomForm.builtUpArea" placeholder="请输入建筑面积" />
        </el-form-item>
        <el-form-item label="算费系数" prop="feeCoefficient">
          <el-input v-model="roomForm.feeCoefficient" placeholder="请输入算费系数" />
        </el-form-item>
        <el-form-item label="房屋状态" prop="state">
          <el-select v-model="roomForm.state" placeholder="请选择房屋状态" style="width: 380px">
            <el-option v-for="dict in sys_room_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="roomType">
          <el-select v-model="roomForm.roomType" placeholder="请选择" style="width: 380px">
            <el-option v-for="dict in sys_room_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="室内面积" prop="roomArea">
          <el-input v-model="roomForm.roomArea" placeholder="请输入室内面积" />
        </el-form-item>
        <el-form-item label="租金" prop="roomRent">
          <el-input v-model="roomForm.roomRent" placeholder="请输入租金" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="roomForm.remark" placeholder="请输入内容" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonRoomLoading" type="primary" @click="submitRoomForm">确 定</el-button>
          <el-button @click="roomCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改楼栋对话框 -->
    <el-dialog v-model="floorDialog.visible" :title="floorDialog.title" append-to-body width="500px">
      <el-form ref="floorFormRef" :model="floorForm" :rules="floorRules" label-width="80px">
        <el-form-item label="楼编号" prop="floorNum">
          <el-input v-model="floorForm.floorNum" placeholder="请输入楼编号" />
        </el-form-item>
        <el-form-item label="楼名称" prop="name">
          <el-input v-model="floorForm.name" placeholder="请输入楼名称" />
        </el-form-item>
        <el-form-item label="建筑面积" prop="floorArea">
          <el-input v-model="floorForm.floorArea" placeholder="请输入建筑面积" />
        </el-form-item>
        <el-form-item label="楼栋排序" prop="seq">
          <el-input v-model="floorForm.seq" placeholder="请输入楼栋排序" />
        </el-form-item>
        <el-form-item label="经度" prop="lat">
          <el-input v-model="floorForm.lat" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="lng">
          <el-input v-model="floorForm.lng" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="floorForm.remark" placeholder="请输入内容" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonFloorLoading" type="primary" @click="submitFloorForm">确 定</el-button>
          <el-button @click="floorCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改房产单元对话框 -->
    <el-dialog v-model="unitDialog.visible" :title="unitDialog.title" append-to-body width="500px">
      <el-form ref="buildingUnitFormRef" :model="unitForm" :rules="unitRules" label-width="100px">
        <el-form-item label="单元编号" prop="unitNum">
          <el-input v-model="unitForm.unitNum" placeholder="请输入单元编号" />
        </el-form-item>
        <el-form-item label="单元名称" prop="name">
          <el-input v-model="unitForm.name" placeholder="请输入单元名称" />
        </el-form-item>
        <el-form-item label="总层数" prop="layerCount">
          <el-input v-model="unitForm.layerCount" placeholder="请输入总层数" />
        </el-form-item>
        <el-form-item label="是否有电梯" prop="lift">
          <el-select v-model="unitForm.lift" placeholder="请选择">
            <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单元面积" prop="unitArea">
          <el-input v-model="unitForm.unitArea" placeholder="请输入单元面积" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="unitForm.remark" placeholder="请输入内容" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonUnitLoading" type="primary" @click="submitUnitForm">确 定</el-button>
          <el-button @click="unitCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" name="Floor" setup>
import { addFloor, delFloor, listFloor, updateFloor } from "@/api/system/floor";
import { FloorForm, FloorQuery } from "@/api/system/floor/types";
import type Node from "element-plus/es/components/tree/src/model/node";
import { listCommunity } from "@/api/system/community";
import { addBuildingUnit, delBuildingUnit, listBuildingUnit, updateBuildingUnit } from "@/api/system/buildingUnit";
import { BuildingUnitForm, BuildingUnitQuery } from "@/api/system/buildingUnit/types";
import {
  addBuildingRoom,
  delBuildingRoom,
  getBuildingRoom,
  listBuildingRoom,
  updateBuildingRoom
} from "@/api/system/buildingRoom";
import { BuildingRoomForm, BuildingRoomQuery, BuildingRoomVO } from "@/api/system/buildingRoom/types";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  sys_yes_no,
  sys_room_type,
  sys_room_state, sys_section_list, sys_apartment_list
} = toRefs<any>(proxy?.useDict("sys_yes_no", "sys_room_type", "sys_room_state", "sys_section_list", "sys_apartment_list"));
const currentNode = ref<Node>();
const currentResolveMap = ref(new Map<number, any>());

const props = {
  label: "name",
  children: "zones",
  isLeaf: "leaf"
};

const handleClick = (data: any, node: Node) => {
  currentNode.value = node;
  floorAddFlag.value = node.level !== 1;
  unitAddFlag.value = node.level !== 2;
  roomAddFlag.value = node.level !== 3;
  floorSingle.value = node.level !== 2;
  floorMultiple.value = node.level !== 2;
  unitSingle.value = node.level !== 3;
  unitMultiple.value = node.level !== 3;
  if (currentNode.value?.level == 1) {
    queryParams.value.communityId = currentNode.value.data.communityId;
    queryParams.value.floorId = undefined;
    queryParams.value.roomNum = undefined;
  }
  if (currentNode.value?.level == 2) {
    queryParams.value.communityId = currentNode.value.data.communityId;
    queryParams.value.floorId = currentNode.value.data.floorId;
    queryParams.value.roomNum = undefined;
  }
  if (currentNode.value?.level == 3) {
    queryParams.value.communityId = currentNode.value.data.communityId;
    queryParams.value.floorId = currentNode.value.data.floorId;
    queryParams.value.roomNum = currentNode.value.data.roomNum;
  }
  getList();
};

const loadNode = async (node: Node, resolve: (data: any[]) => void) => {
  console.log("loadNode", node, "resolve");
  currentResolveMap.value.set(node.id, resolve);
  if (node.level === 0) {
    let res = await listCommunity();
    return resolve(res.rows);
  }
  if (node.level === 1) {
    let param: FloorQuery = { communityId: node.data.communityId };
    let res = await listFloor(param);
    return resolve(res.rows);
  }
  if (node.level === 2) {
    let param: BuildingUnitQuery = {
      floorId: node.data.floorId
    };
    let res = await listBuildingUnit(param);
    const rows = res.rows.map(obj => {
      obj.leaf = true;
      return obj;
    });
    return resolve(rows);
  }
  if (node.level >= 3) {
    return resolve([]);
  }
};
const buildingRoomList = ref<BuildingRoomVO[]>([]);
const buttonRoomLoading = ref(false);
const buttonFloorLoading = ref(false);
const buttonUnitLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const floorSingle = ref(true);
const floorMultiple = ref(true);
const unitSingle = ref(true);
const unitMultiple = ref(true);
const roomSingle = ref(true);
const roomMultiple = ref(true);
const floorAddFlag = ref(true);
const unitAddFlag = ref(true);
const roomAddFlag = ref(true);

const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const buildingRoomFormRef = ref<ElFormInstance>();
const floorFormRef = ref<ElFormInstance>();
const roomDialog = reactive<DialogOption>({
  visible: false,
  title: ""
});
const floorDialog = reactive<DialogOption>({
  visible: false,
  title: ""
});
const initRoomFormData: BuildingRoomForm = {
  roomId: undefined,
  roomNum: undefined,
  unitId: undefined,
  layer: undefined,
  section: undefined,
  apartment: undefined,
  builtUpArea: undefined,
  feeCoefficient: undefined,
  userId: undefined,
  state: undefined,
  communityId: undefined,
  roomType: undefined,
  roomSubType: undefined,
  roomArea: undefined,
  roomRent: undefined,
  status: undefined,
  remark: undefined
};
const roomData = reactive<PageData<BuildingRoomForm, BuildingRoomQuery>>({
  form: { ...initRoomFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roomNum: undefined,
    unitId: undefined,
    layer: undefined,
    section: undefined,
    apartment: undefined,
    builtUpArea: undefined,
    feeCoefficient: undefined,
    userId: undefined,
    state: undefined,
    communityId: undefined,
    roomType: undefined,
    roomSubType: undefined,
    roomArea: undefined,
    roomRent: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    roomId: [
      { required: true, message: "房屋ID不能为空", trigger: "blur" }
    ],
    roomNum: [
      { required: true, message: "房屋编号不能为空", trigger: "blur" }
    ],
    unitId: [
      { required: true, message: "单元编号不能为空", trigger: "blur" }
    ],
    layer: [
      { required: true, message: "层数不能为空", trigger: "blur" }
    ],
    section: [
      { required: true, message: "室不能为空", trigger: "blur" }
    ],
    apartment: [
      { required: true, message: "户型不能为空", trigger: "blur" }
    ],
    builtUpArea: [
      { required: true, message: "建筑面积不能为空", trigger: "blur" }
    ],
    feeCoefficient: [
      { required: true, message: "算费系数不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    state: [
      { required: true, message: "房屋状态，如房屋出售等，请查看state 表不能为空", trigger: "blur" }
    ],
    communityId: [
      { required: true, message: "小区编号不能为空", trigger: "blur" }
    ],
    roomType: [
      { required: true, message: "房屋类型不能为空", trigger: "change" }
    ],
    roomArea: [
      { required: true, message: "室内面积不能为空", trigger: "blur" }
    ],
    roomRent: [
      { required: true, message: "租金不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form: roomForm, rules: roomRules } = toRefs(roomData);
/** 查询房屋列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBuildingRoom(queryParams.value);
  buildingRoomList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const roomCancel = () => {
  roomReset();
  roomDialog.visible = false;
};

/** 取消按钮 */
const floorCancel = () => {
  floorReset();
  floorDialog.visible = false;
};

/** 表单重置 */
const roomReset = () => {
  roomForm.value = { ...initRoomFormData };
  buildingRoomFormRef.value?.resetFields();
};
/** 表单重置 */
const floorReset = () => {
  floorForm.value = { ...initFloorFormData };
  floorFormRef.value?.resetFields();
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: BuildingRoomVO[]) => {
  ids.value = selection.map(item => item.roomId);
  roomSingle.value = selection.length != 1;
  roomMultiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAddRoom = () => {
  roomReset();
  roomDialog.visible = true;
  roomDialog.title = "添加房屋";
};
/** 添加楼栋 */
const handleAddFloor = async () => {
  if (currentNode.value?.level != 1) {
    proxy?.$modal.msgError("请选择小区");
    return;
  }
  floorReset();
  floorDialog.visible = true;
  floorDialog.title = "添加楼栋";
};
/** 修改楼栋*/
const handleUpdateFloor = async () => {
  if (currentNode.value?.level != 2) {
    proxy?.$modal.msgError("请选择需要修改的楼栋");
    return;
  }
  floorReset();
  Object.assign(floorForm.value, currentNode.value?.data);
  floorDialog.visible = true;
  floorDialog.title = "修改楼栋";
};
/** 删除楼栋 */
const handleDeleteFloor = async () => {
  if (currentNode.value?.level != 2) {
    proxy?.$modal.msgError("请选择需要删除的楼栋");
    return;
  }
  let _floorIds = currentNode.value?.data.floorId;
  await proxy?.$modal.confirm("是否确认删除楼栋编号为\"" + _floorIds + "\"的数据项？").finally(() => loading.value = false);
  await delFloor(_floorIds);
  proxy?.$modal.msgSuccess("删除成功");
  await refreshParentTree();
};
const refreshParentTree = async () => {
  if (currentNode.value) {
    await loadNode(currentNode.value?.parent, currentResolveMap.value.get(currentNode.value?.parent.id));
  }
  currentNode.value = undefined;
};
const refreshTree = async () => {
  if (currentNode.value) {
    await loadNode(currentNode.value, currentResolveMap.value.get(currentNode.value?.id));
  }
  currentNode.value = undefined;
};
/** 添加单元*/
const handleAddBuildingUnit = async () => {
  if (currentNode.value?.level != 2) {
    proxy?.$modal.msgError("请选择楼栋");
    return;
  }
  unitReset();
  unitDialog.visible = true;
  unitDialog.title = "添加单元";
};
/** 修改单元*/
const handleUpdateBuildingUnit = () => {
  if (currentNode.value?.level != 3) {
    proxy?.$modal.msgError("请选择需要修改的单元");
    return;
  }
  console.log("currentNode.value?.data", currentNode.value?.data);
  unitReset();
  Object.assign(unitForm.value, currentNode.value?.data);
  unitDialog.visible = true;
  unitDialog.title = "修改单元";
};
/** 删除单元*/
const handleDeleteBuildingUnit = async () => {
  if (currentNode.value?.level != 3) {
    proxy?.$modal.msgError("请选择需要删除的单元");
    return;
  }
  let _unitId = currentNode.value?.data.unitId;
  await proxy?.$modal.confirm("是否确认删除单元编号为\"" + _unitId + "\"的数据项？").finally(() => loading.value = false);
  await delBuildingUnit(_unitId);
  proxy?.$modal.msgSuccess("删除成功");
  await refreshParentTree();
};
/** 修改按钮操作 */
const handleUpdateRoom = async (row?: BuildingRoomVO) => {
  roomReset();
  const _roomId = row?.roomId || ids.value[0];
  const res = await getBuildingRoom(_roomId);
  Object.assign(roomForm.value, res.data);
  roomDialog.visible = true;
  roomDialog.title = "修改房屋";
};

/** 提交按钮 */
const submitRoomForm = () => {
  if (currentNode.value?.level != 3 && !roomForm.value.roomId) {
    proxy?.$modal.msgError("请选择单元");
    return;
  }
  buildingRoomFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonRoomLoading.value = true;
      if (roomForm.value.roomId) {
        await updateBuildingRoom(roomForm.value).finally(() => buttonRoomLoading.value = false);
      } else {
        roomForm.value.floorId = currentNode.value?.data.floorId;
        roomForm.value.unitId = currentNode.value?.data.unitId;
        roomForm.value.communityId = currentNode.value?.data.communityId;
        await addBuildingRoom(roomForm.value).finally(() => buttonRoomLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      roomDialog.visible = false;
      await getList();
    }
  });
};
/** 提交按钮 */
const submitFloorForm = () => {
  floorFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonFloorLoading.value = true;
      if (floorForm.value.floorId) {
        await updateFloor(floorForm.value).finally(() => buttonFloorLoading.value = false);
        proxy?.$modal.msgSuccess("修改成功");
        floorDialog.visible = false;
        await refreshParentTree();
      } else {
        floorForm.value.communityId = currentNode.value?.data.communityId;
        await addFloor(floorForm.value).finally(() => buttonFloorLoading.value = false);
        proxy?.$modal.msgSuccess("增加成功");
        floorDialog.visible = false;
        await refreshTree();
      }
    }
  });
};
const initFloorFormData: FloorForm = {
  floorId: undefined,
  floorNum: undefined,
  name: undefined,
  communityId: undefined,
  floorArea: undefined,
  seq: undefined,
  lat: undefined,
  lng: undefined,
  status: undefined,
  remark: undefined
};
const floorData = reactive<PageData<FloorForm, FloorQuery>>({
  form: { ...initFloorFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    floorNum: undefined,
    name: undefined,
    communityId: undefined,
    floorArea: undefined,
    seq: undefined,
    lat: undefined,
    lng: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    floorId: [
      { required: true, message: "楼ID不能为空", trigger: "blur" }
    ],
    floorNum: [
      { required: true, message: "楼编号不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "楼名称不能为空", trigger: "blur" }
    ],
    communityId: [
      { required: true, message: "小区编号不能为空", trigger: "blur" }
    ],
    floorArea: [
      { required: true, message: "建筑面积不能为空", trigger: "blur" }
    ],
    seq: [
      { required: true, message: "楼栋排序不能为空", trigger: "blur" }
    ],
    lat: [
      { required: true, message: "经度不能为空", trigger: "blur" }
    ],
    lng: [
      { required: true, message: "纬度不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ]
  }
});

const { form: floorForm, rules: floorRules } = toRefs(floorData);
const unitDialog = reactive<DialogOption>({
  visible: false,
  title: ""
});
const buildingUnitFormRef = ref<ElFormInstance>();
const initUnitFormData: BuildingUnitForm = {
  unitId: undefined,
  unitNum: undefined,
  floorId: undefined,
  layerCount: undefined,
  lift: undefined,
  unitArea: undefined,
  status: undefined,
  remark: undefined,
  name: undefined
};
const unitData = reactive<PageData<BuildingUnitForm, BuildingUnitQuery>>({
  form: { ...initUnitFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    unitNum: undefined,
    floorId: undefined,
    communityId: undefined,
    layerCount: undefined,
    lift: undefined,
    unitArea: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    unitId: [
      { required: true, message: "单元编号不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "单元名称不能为空", trigger: "blur" }
    ],
    unitNum: [
      { required: true, message: "单元编号不能为空", trigger: "blur" }
    ],
    floorId: [
      { required: true, message: "楼ID不能为空", trigger: "blur" }
    ],
    communityId: [
      { required: true, message: "小区编号不能为空", trigger: "blur" }
    ],
    layerCount: [
      { required: true, message: "总层数不能为空", trigger: "blur" }
    ],
    lift: [
      { required: true, message: "是否有电梯不能为空", trigger: "blur" }
    ],
    unitArea: [
      { required: true, message: "单元面积不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ]
  }
});

const { form: unitForm, rules: unitRules } = toRefs(unitData);
/** 删除按钮操作 */
const handleDeleteRoom = async (row?: BuildingRoomVO) => {
  const _roomIds = row?.roomId || ids.value;
  await proxy?.$modal.confirm("是否确认删除房屋编号为\"" + _roomIds + "\"的数据项？").finally(() => loading.value = false);
  await delBuildingRoom(_roomIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};

/** 导出按钮操作 */
const handleExportRoom = () => {
  proxy?.download("system/buildingRoom/export", {
    ...queryParams.value
  }, `buildingRoom_${new Date().getTime()}.xlsx`);
};
/** 取消按钮 */
const unitCancel = () => {
  unitReset();
  unitDialog.visible = false;
};
/** 表单重置 */
const unitReset = () => {
  unitForm.value = { ...initUnitFormData };
  buildingUnitFormRef.value?.resetFields();
};

/** 提交按钮 */
const submitUnitForm = () => {
  buildingUnitFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonUnitLoading.value = true;
      if (unitForm.value.unitId) {
        await updateBuildingUnit(unitForm.value).finally(() => buttonUnitLoading.value = false);
        proxy?.$modal.msgSuccess("修改成功");
        unitDialog.visible = false;
        await refreshParentTree();
      } else {
        console.log("currentNode.value", currentNode.value);
        unitForm.value.communityId = currentNode.value?.data.communityId;
        unitForm.value.floorId = currentNode.value?.data.floorId;
        await addBuildingUnit(unitForm.value).finally(() => buttonUnitLoading.value = false);
        proxy?.$modal.msgSuccess("新增成功");
        unitDialog.visible = false;
        await refreshTree();
      }
    }
  });
};

onMounted(() => {
  getList();
});
</script>
